<template>
	<el-upload
		:data="uploadParams"
		v-bind="uploadConfig"
		:file-list="fileList"
		:accept="uploadAccept"
		:action="uploadFileUrl"
		:headers="uploadHeader"
		:on-error="handleUploadError"
		:on-remove="handleUploadRemove"
		:on-change="handleUploadChange"
		:on-success="handleUploadSuccess"
		:before-upload="handleBeforeUpload"
	>
		<el-button type="primary" icon="el-icon-upload2">上传文件</el-button>
		<div slot="tip" class="tips">
			<label>建议：上传文件</label>
			<span v-if="!!size">大小不超过{{ size }}MB</span>
			<span v-if="!!size && !!accept">且</span>
			<span v-if="!!accept">格式为{{ accept }}</span>
		</div>
	</el-upload>
</template>

<script>
import { mapGetters } from 'vuex';
import emitter from 'element-ui/src/mixins/emitter';
export default {
	name: 'swFileUploader',
	mixins: [emitter],
	props: {
		value: { type: Array, default: () => [] },
		// 文件大小, 例如['png', 'jpg', 'jpeg']
		size: { type: String, default: '1000' },
		// 文件类型, 例如['png', 'jpg', 'jpeg']
		accept: { type: String, default: '' },
		//上传类型
		type: { type: String, default: '3' }
	},
	data() {
		let baseURL = !window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl;
		return {
			fileList: this.value,
			uploadFileUrl: `${baseURL}tbSysAttachment/upload`, // 上传的图片服务器地址
			uploadParams: { showType: '5', type: this.type },
			uploadConfig: {
				ref: 'upload',
				multiple: true,
				class: 'multiple_file_upload'
			}
		};
	},
	watch: {
		value(arr) {
			this.fileList = arr;
		},
		fileList(arr) {
			console.log(arr);
			this.$emit('input', arr);
			this.dispatch('ElFormItem', 'el.form.change', [arr]);
		}
	},
	computed: {
		...mapGetters(['token']),
		uploadAccept() {
			let suffixArr = this.accept.split(',').map((item) => '.' + item);
			return suffixArr.join();
		},
		uploadHeader() {
			return { Authorization: this.token };
		}
	},
	methods: {
		handleBeforeUpload(file) {},

		// 文件个数超出
		handleExceed() {
			this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
		},

		//上传变化
		handleUploadChange(file, fileList) {
			this.fileList = fileList.map((item) => {
				let obj = { ...item };
				if (!!item.response) {
					let resData = this.$detailData(item.response?.data);
					obj = { ...obj, ...resData };
				}
				delete obj.response;
				return obj;
			});
		},

		// 上传成功回调
		handleUploadSuccess(res, file, fileList) {
			if (res.code !== '0') {
				let index = fileList.findIndex((n) => n.uid === file.uid);
				fileList.splice(index, 1);
			}
		},

		//删除上传文件
		handleUploadRemove(file, fileList) {
			this.fileList = fileList.map((item) => {
				let obj = { ...item };
				if (!!item.response) {
					let resData = this.$detailData(item.response?.data);
					obj = { ...obj, ...resData };
				}
				delete obj.response;
				return obj;
			});
		},

		// 上传失败
		handleUploadError() {}
	}
};
</script>

<style lang="scss" scoped>
.multiple_file_upload .tips {
	color: #999;
	line-height: 20px;
	margin-top: 10px;
}
</style>
